﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Web;
using System.Web.Mvc;

namespace DHQGHN.PM2
{
    public class ToolTipAttribute : DescriptionAttribute
    {
        //public string ResourceKey { get; set; }
        //public string ResourceKey { get; set; }
        /// <summary>
        /// Hidden to force a message to be displayed
        /// </summary>
        private ToolTipAttribute()
            : base("")
        {

        }

        /// <summary>
        /// Tool tip attribute for adding helper messages to model entities.
        /// </summary>
        /// <param name="description">

        public ToolTipAttribute(string resourceKey)
            : base(GetMessageFromResource(resourceKey))
        {
            //ResourceKey = resourceKey;
        }
        private static string GetMessageFromResource(string resourceKey)
        {
            // TODO: Return the string from the resource file
            return TooltipResource.ResourceManager.GetString(resourceKey);
        }

    }
    public static class HtmlHelpers
    {
        private static string PerformMessageBuild(string name, string description)
        {

            StringBuilder sb = new StringBuilder();
            //sb.Append("<span ");
            //sb.Append("class='tooltipmsgspan-" + name.ToLower() + "' ");
            //sb.Append("style='display:none;'>");
            //sb.Append(description);
            //sb.Append("</span>");
            sb.Append(description);
            return sb.ToString();
        }
        public static MvcHtmlString ToolTipMessageFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            string tooltopMessage = string.Empty;
            var exp = (MemberExpression)expression.Body;
            foreach (Attribute attribute in exp.Expression.Type.GetProperty(exp.Member.Name).GetCustomAttributes(false))
            {
                if (typeof(ToolTipAttribute) == attribute.GetType())
                {
                    var tooltipHelper = (ToolTipAttribute)attribute;
                    tooltopMessage = PerformMessageBuild(exp.Member.Name, tooltipHelper.Description);
                    return MvcHtmlString.Create(tooltopMessage);
                }
                if (typeof(RequiredAttribute) == attribute.GetType())
                {
                    var tooltipHelper = (RequiredAttribute)attribute;
                    if (tooltopMessage == string.Empty)
                    {
                        tooltopMessage = PerformMessageBuild(exp.Member.Name, tooltipHelper.ErrorMessage);
                    }

                }
            }
            return MvcHtmlString.Create(tooltopMessage);
        }
    }
}